﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DeleteFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            ConfigurationFile configFile = new ConfigurationFile();
            configFile.ReadXml(DeleteFiles.Default.ConfigFilePath);
            try
            {
                WriteLog("====================Start====================");
                foreach (ConfigurationFile.ConfigRow configDataRow in configFile.Config.Rows)
                {
                     
                    DirectoryInfo parentDir = new DirectoryInfo(configDataRow.DirectoryPath);
                    WriteLog("Starting to Read Parent directory "+configDataRow.DirectoryPath);
                    //Note:- we will always get first level subdirectories regardless configDataRow.ActiononSubDirectoriesAlso value
                    DirectoryInfo []childDir=parentDir.GetDirectories("*", configDataRow.ActiononSubDirectoriesAlso == "True" ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
                    WriteLog("Total " + childDir.Length.ToString() + " child directories");
                    if (childDir.Length > 0)
                    {
                        foreach (DirectoryInfo dirToWorkon in childDir)
                        {
                            Deletefilesinfolder(dirToWorkon, configDataRow.FileExtension, int.Parse(configDataRow.DeleteNDayoldFiles));
                        }
                    }
                    else
                    {
                        Deletefilesinfolder(parentDir, configDataRow.FileExtension, int.Parse(configDataRow.DeleteNDayoldFiles));
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.ToString());
            }
            WriteLog("====================End====================");
        }

        private static void Deletefilesinfolder(DirectoryInfo dirToWorkon, String fileExtensions, int deleteNDayoldFiles)
        {
            double noofDays = 0;
            WriteLog("Starting to Read directory " + dirToWorkon.FullName);
            FileInfo[] filesMightbeDeleted = dirToWorkon.GetFiles(fileExtensions);
            WriteLog("Total files " + filesMightbeDeleted.Length.ToString());
            foreach (FileInfo fl in filesMightbeDeleted)
            {
                noofDays = fl.LastWriteTime.Subtract(DateTime.Today).TotalDays;
                if (DeleteFiles.Default.LogFullDetails == true)
                {
                    WriteLog("Checking file " + fl.Name + " Modified " + noofDays.ToString() + " days ago");
                }
                if (Math.Abs(noofDays) > deleteNDayoldFiles)
                {
                    Console.WriteLine("file " + fl.Name + " deleted");
                    fl.Delete();
                    WriteLog("File " + fl.Name + " deleted");
                }
            }
        }

        private static void WriteLog(string logText_)
        {
            string fileUrl = DeleteFiles.Default.LogFilePath + "\\" + DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.ToString("hh") + "_" + DateTime.Now.ToString("tt") + ".txt";
            if (!Directory.Exists(DeleteFiles.Default.LogFilePath))
            {
                Directory.CreateDirectory(DeleteFiles.Default.LogFilePath);
            }

            
            StreamWriter logWriter = null;
            try
            {
                logWriter = File.AppendText(fileUrl);
                logWriter.WriteLine(DateTime.Now.ToString()+" ====> "+ logText_);
            }
            finally
            {
                if (logWriter != null)
                {
                    logWriter.Flush();
                    logWriter.Close();
                    logWriter = null;
                }
            }
        }
    }
}
